import forge from 'node-forge';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 创建ssl目录(如果不存在)
const sslDir = path.join(__dirname, 'ssl');
if (!fs.existsSync(sslDir)) {
  fs.mkdirSync(sslDir);
}

// 生成密钥对
const keys = forge.pki.rsa.generateKeyPair(2048);

// 创建证书
const cert = forge.pki.createCertificate();
cert.publicKey = keys.publicKey;
cert.serialNumber = '01';
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);

// 设置证书属性
const attrs = [
  { name: 'commonName', value: 'localhost' },
  { name: 'organizationName', value: 'MID Decoder' },
  { name: 'countryName', value: 'CN' }
];
cert.setSubject(attrs);
cert.setIssuer(attrs);

// 签名证书
cert.sign(keys.privateKey, forge.md.sha256.create());

// 转换为PEM格式
const privateKeyPem = forge.pki.privateKeyToPem(keys.privateKey);
const certPem = forge.pki.certificateToPem(cert);

// 保存文件
fs.writeFileSync(path.join(sslDir, 'key.pem'), privateKeyPem);
fs.writeFileSync(path.join(sslDir, 'cert.pem'), certPem);

console.log('SSL证书已生成:');
console.log(`- 私钥: ${path.join(sslDir, 'key.pem')}`);
console.log(`- 证书: ${path.join(sslDir, 'cert.pem')}`);